import React from 'react';
import {
  Button,
  Empty,
  Form,
  Modal,
  Popconfirm,
  Select,
  SideSheet,
  Table,
  Tag,
  TextArea,
  Toast,
  Tooltip,
} from '@douyinfe/semi-ui';
import bookmarkStyle from './index.less';
import {
  IllustrationNoContent,
  IllustrationNoContentDark,
} from '@douyinfe/semi-illustrations';
import BookmarkAPI from '@/api/model/bookmark';

const { Column } = Table;
export default class Bookmark extends React.Component {
  private formApi: any;

  constructor(props: any) {
    super(props);
    this.state = {
      category_id: '',
      data: [],
      formData: {},
      initValues: {},
      bookTypeSelect: [],
      tableLoading: false,
      visible: false,
      isCreate: true,
      modalVisible: false,
      pagination: {
        page_size: 10,
        page_current: 1,
        total: 0,
      },
    };
    this.handlePageChange = this.handlePageChange.bind(this);
    this.getbookTypeSelect = this.getbookTypeSelect.bind(this);
    this.getBookList = this.getBookList.bind(this);
    this.changeSideSheet = this.changeSideSheet.bind(this);
    this.getFormApi = this.getFormApi.bind(this);
    this.editBookmark = this.editBookmark.bind(this);
    this.changeBookmarkModal = this.changeBookmarkModal.bind(this);
    this.changeBookmarkSelect = this.changeBookmarkSelect.bind(this);
  }

  componentDidMount() {
    this.getbookTypeSelect();
    this.getBookList();
  }

  async getbookTypeSelect() {
    const res = await BookmarkAPI.CategorySelect();
    this.setState({
      bookTypeSelect: res.data,
    });
  }

  async getBookList() {
    const { category_id }: any = this.state;
    const data = { category_id };
    if (category_id == 0) delete data.category_id;
    this.setState({
      tableLoading: true,
    });
    const { pagination }: any = this.state;
    const res = await BookmarkAPI.BookmarkList({ ...pagination, ...data });
    this.setState({
      data: res.data.data,
      tableLoading: false,
      pagination: {
        ...pagination,
        total: res.data.total,
      },
    });
  }

  async handlePageChange(page_current: number) {
    const { pagination }: any = this.state;
    await this.setState({
      pagination: {
        ...pagination,
        page_current,
      },
    });
    await this.getBookList();
  }

  changeSideSheet() {
    const { visible }: any = this.state;
    this.setState({
      visible: !visible,
      isCreate: true,
    });
    const { category_id }: any = this.state;
    if (category_id !== 0 && category_id) {
      setTimeout(() => {
        const { formData }: any = this.state;
        this.formApi.setValue('category_id', category_id + '');
      });
    }
  }

  editBookmark() {
    this.setState({
      visible: true,
      isCreate: false,
    });
    setTimeout(() => {
      const { formData }: any = this.state;
      this.formApi.setValue('id', formData.id);
      this.formApi.setValue('title', formData.title);
      this.formApi.setValue('category_id', formData.category_id + '');
      this.formApi.setValue('link', formData.link);
      this.formApi.setValue('desc', formData.desc);
      this.formApi.setValue('sort', formData.sort);
    });
  }

  getFormApi(formApi: any) {
    this.formApi = formApi;
  }

  async submitForm(values: any) {
    const { isCreate }: any = this.state;
    let res: any = {};
    if (isCreate) {
      res = await BookmarkAPI.BookmarkCreate(values);
    } else {
      res = await BookmarkAPI.BookmarkUpdate(values);
    }
    if (res.status) {
      Toast.success({
        content: `${isCreate ? '创建' : '修改'}书签成功！`,
        duration: 3,
      });
      await this.changeSideSheet();
      await this.getBookList();
    } else {
      Toast.error({
        content: res.data.error,
        duration: 3,
      });
    }
  }

  async delBookmark() {
    const { formData }: any = this.state;
    const res: any = await BookmarkAPI.BookmarkDel({ id: formData.id });
    if (res.status) {
      Toast.success({
        content: '删除书签成功',
        duration: 3,
      });
      await this.getBookList();
    } else {
      Toast.error({
        content: res.data.error,
        duration: 3,
      });
    }
    console.log('formData', formData);
  }

  changeBookmarkModal() {
    const { modalVisible }: any = this.state;
    this.setState({
      modalVisible: !modalVisible,
    });
  }

  async changeBookmarkSelect(category_id: any) {
    await this.setState({
      category_id,
    });
    await this.getBookList();
  }

  render() {
    const {
      data,
      pagination,
      tableLoading,
      bookTypeSelect,
      visible,
      isCreate,
      initValues,
      modalVisible,
      formData,
    }: any = this.state;
    const emptyStyle = {
      padding: 30,
    };
    return (
      <div
        className={[bookmarkStyle.bookmark_container, 'content_container'].join(
          ' ',
        )}
      >
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <Button
            style={{ marginBottom: '1rem' }}
            theme="light"
            onClick={this.changeSideSheet}
          >
            添加书签
          </Button>
          <Select
            placeholder="书签分类"
            showClear
            style={{ width: 180, marginBottom: '1rem', marginLeft: '1rem' }}
            onChange={(e: any) => this.changeBookmarkSelect(e)}
          >
            {Object.keys(bookTypeSelect).map((key) => (
              <Select.Option key={key} value={key}>
                {bookTypeSelect[key]}
              </Select.Option>
            ))}
          </Select>
        </div>

        <Table
          bordered
          loading={tableLoading}
          empty={
            <Empty
              image={
                <IllustrationNoContent style={{ width: 150, height: 150 }} />
              }
              darkModeImage={
                <IllustrationNoContentDark
                  style={{ width: 150, height: 150 }}
                />
              }
              description={'暂无内容，请添加'}
              style={emptyStyle}
            />
          }
          onRow={(record, index) => {
            return {
              onClick: (event) => {
                this.setState({
                  formData: record,
                });
              },
            };
          }}
          pagination={{
            currentPage: pagination.page_current,
            pageSize: pagination.page_size,
            total: pagination.total,
            onPageChange: this.handlePageChange,
          }}
          dataSource={data}
        >
          {/*<Column title='id' dataIndex='id' key='id' />*/}
          <Column title="书签名称" dataIndex="title" key="title" />
          <Column
            title="书签分类"
            dataIndex="category_id"
            key="category_id"
            render={(e) => {
              return (
                <Tag color="blue" type="light">
                  {' '}
                  {bookTypeSelect[e]}{' '}
                </Tag>
              );
            }}
          />
          <Column
            title="排序"
            dataIndex="sort"
            key="sort"
            sorter={(a: { sort: number }, b: { sort: number }) =>
              a.sort - b.sort > 0 ? 1 : -1
            }
          />
          <Column
            title="浏览量"
            dataIndex="pv"
            key="pv"
            sorter={(a: { sort: number }, b: { sort: number }) =>
              a.sort - b.sort > 0 ? 1 : -1
            }
          />
          <Column
            title="点赞"
            dataIndex="tags_num"
            key="tags_num"
            sorter={(a: { sort: number }, b: { sort: number }) =>
              a.sort - b.sort > 0 ? 1 : -1
            }
          />
          <Column
            title="收藏"
            dataIndex="hoard_num"
            key="hoard_num"
            sorter={(a: { sort: number }, b: { sort: number }) =>
              a.sort - b.sort > 0 ? 1 : -1
            }
          />
          {/*<Column title='链接' dataIndex='link' key='link' />*/}
          <Column title="创建时间" dataIndex="create_time" key="create_time" />
          <Column
            title="操作"
            render={() => (
              <>
                <Tooltip content={'查看书签详情'}>
                  <Button
                    onClick={this.changeBookmarkModal}
                    theme="light"
                    style={{ marginRight: 8 }}
                  >
                    详情
                  </Button>
                </Tooltip>
                <Tooltip content={'编辑书签详情'}>
                  <Button
                    onClick={this.editBookmark}
                    theme="light"
                    style={{ marginRight: 8 }}
                  >
                    编辑
                  </Button>
                </Tooltip>
                {/*// @ts-ignore*/}
                <Popconfirm
                  content="是否确认删除"
                  onConfirm={() => this.delBookmark()}
                >
                  <span style={{ display: 'inline-block' }}>
                    <Tooltip content={'删除书签分类'}>
                      <Button
                        theme="light"
                        type="danger"
                        style={{ marginRight: 8 }}
                      >
                        删除
                      </Button>
                    </Tooltip>
                  </span>
                </Popconfirm>
              </>
            )}
          />
        </Table>
        <BookmarkSideSheet
          visible={visible}
          isCreate={isCreate}
          initValues={initValues}
          bookTypeSelect={bookTypeSelect}
          submitForm={(values: any) => this.submitForm(values)}
          getFormApi={(e: any) => this.getFormApi(e)}
          change={this.changeSideSheet}
        />
        <BookmarkModal
          modalVisible={modalVisible}
          changeBookmarkModal={this.changeBookmarkModal}
          formData={formData}
        />
      </div>
    );
  }
}

const BookmarkSideSheet = (props: any) => {
  const style = { width: '100%' };
  const {
    isCreate,
    visible,
    change,
    getFormApi,
    initValues,
    bookTypeSelect,
    submitForm,
  } = props;

  const { Input, Select, TextArea } = Form;

  return (
    <>
      <SideSheet
        title={isCreate ? '创建书签' : '编辑书签'}
        visible={visible}
        onCancel={change}
      >
        <Form
          getFormApi={getFormApi}
          initValues={initValues}
          style={{ padding: 10, width: '100%' }}
          onSubmit={(values) => submitForm(values)}
        >
          {/*// @ts-ignore*/}

          <Input
            field="title"
            label="书签名称"
            placeholder="请输入书签名称"
            style={style}
            trigger="blur"
            rules={[{ required: true, message: '书签名称不能为空' }]}
          />
          {/*// @ts-ignore*/}

          <Select
            field="category_id"
            style={style}
            label="书签分类"
            placeholder="请选择书签的分类"
            rules={[{ required: true, message: '请选择书签的分类' }]}
          >
            {Object.keys(bookTypeSelect).map((key) => (
              <Select.Option key={key} value={key}>
                {bookTypeSelect[key]}
              </Select.Option>
            ))}
          </Select>
          {/*// @ts-ignore*/}

          <Input
            field="link"
            label="书签链接"
            placeholder="请输入书签链接"
            style={style}
            trigger="blur"
            rules={[{ required: true, message: '书签链接不能为空' }]}
          />
          {/*// @ts-ignore*/}
          <Input
            style={style}
            field="sort"
            label="排序"
            placeholder="请填排序"
          />
          {/*// @ts-ignore*/}
          <TextArea
            style={{ ...style, height: 120 }}
            field="desc"
            label="书签描述"
            placeholder="请填写书签描述"
          />
          <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
            <Button style={{ marginRight: 8 }} htmlType="reset">
              重 置
            </Button>
            <Button
              type="primary"
              htmlType="submit"
              className="btn-margin-right"
            >
              提 交
            </Button>
          </div>
        </Form>
      </SideSheet>
    </>
  );
};

const BookmarkModal = (props: any) => {
  const { modalVisible, changeBookmarkModal, formData } = props;
  return (
    <Modal
      title={formData.title}
      visible={modalVisible}
      onOk={changeBookmarkModal}
      onCancel={changeBookmarkModal}
      className="modalStyle"
      centered
    >
      {formData.desc}
    </Modal>
  );
};
